package com.zhuyp.shiro.utils;

import java.util.List;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.shiro.codec.Hex;

public class HmacSHA256Utils {

	private static final String KEY = "ZHUYP";

	public static String digest(String content) {
		return digest(KEY,content);
	}

	public static String digest(String key, String content) {
		try {
			Mac mac = Mac.getInstance("HmacSHA256");
			byte[] secretByte = key.getBytes("utf-8");
			byte[] dataBytes = content.getBytes("utf-8");
			SecretKey secret = new SecretKeySpec(secretByte, "HMACSHA256");
			mac.init(secret);
			byte[] doFinal = mac.doFinal(dataBytes);
			char[] hexB = Hex.encode(doFinal);
			return new String(hexB);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static String digest(String key, Map<String, ?> map) {
		StringBuilder s = new StringBuilder();
		for (Object values : map.values()) {
			if (values instanceof String[]) {
				for (String value : (String[]) values) {
					s.append(value);
				}
			} else if (values instanceof List) {
				for (String value : (List<String>) values) {
					s.append(value);
				}
			} else {
				s.append(values);
			}
		}
		return digest(key, s.toString());
	}
	
	public static void main(String[] args) {
		System.out.println(digest("zhuyp1202"));
	}
}
